import { getTpl } from '@/views/tpl-v2'
import { http } from '@/utils/axios'
import { getCurWebsite } from '@/views/common'

const response = require('./pingbo.json')
console.log(response.length)
const pingboMethods = `{
  getLevelCols (zIndex) {
    if (zIndex === 0) {
      return this.list[0].data[0].levels
    }
    if (zIndex === 1) {
      // this.list[0]
      for (let i = 0; i < this.list.length; i++) {
        const { data } = this.list[i]
        if (data && data[0] && data[0].children && data[0].children[0]) {
          return data[0].children[0].levels
        }
      }
    }
    return {}
  },
  getLabel(level) {
    if (level === 'PL')  return '会员'
    if (level === 'AG')  return '代理'
    if (level === 'MA')  return '总代'
    if (level === 'SMA')  return '高级总代'
    return level
  }
}`
const pingboTpl = `
<div id="app">
<div style="padding: 10px;">
  <div v-for="(t, i) in list" :key="i" class="table-item">
    <h3 v-if="t.name" v-cloak>{{t.name}}</h3>
    <el-table
      :data="t.data"
      border
      fit
      :header-cell-style="{backgroundColor: '#f5f7fa', textAlign: 'center'}"
      :cell-style="{'text-align':'center'}"
      style="width: 100%;"
    >
      <el-table-column align="center" prop="userCode" label="用户名称"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="level" label="级别">
        <template slot-scope="{ row }">
          <span>{{ getLabel(row.level) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="currency" label="货币"></el-table-column>
      <el-table-column prop="localTurnover" label="营业额"> </el-table-column>
      <el-table-column prop="localVolume" label="总投注量"> </el-table-column>
      <el-table-column prop="localGrossComm" label="总佣金"> </el-table-column>
      <el-table-column prop="payout" label="派彩"> </el-table-column>
      <el-table-column v-for="(item, key) in getLevelCols(0)" :key="key" :prop="key" :label="getLabel(key)">
        <el-table-column :prop="'levels.' + key + '.localPnl'" label="输/赢"></el-table-column>
        <el-table-column :prop="'levels.' + key + '.localNettCommission'" label="佣金"></el-table-column>
        <el-table-column :prop="'levels.' + key + '.localTotal'" label="总计"></el-table-column>
      </el-table-column>
      <el-table-column prop="loginLevelWinLoss" label="公司"> </el-table-column>
    </el-table>
    <div style="padding-left: 20px;" v-for="sub in t.data" :key="sub.userCode">
      <h4 v-if="sub.children && sub.children.length" v-cloak :key="i">{{ sub.userCode }}</h4>
      <el-table
        v-if="sub.children && sub.children.length"
        :data="sub.children"
        border
        fit
        :header-cell-style="{backgroundColor: '#f5f7fa', textAlign: 'center'}"
        :cell-style="{'text-align':'center'}"
        style="width: 100%;"
      >
        <el-table-column prop="userCode" label="用户名称"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="level" label="级别">
          <template slot-scope="{ row }">
            <span>{{ getLabel(row.level) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="currency" label="货币"></el-table-column>
        <el-table-column prop="localTurnover" label="营业额"> </el-table-column>
        <el-table-column prop="localVolume" label="总投注量"> </el-table-column>
        <el-table-column prop="localGrossComm" label="总佣金"> </el-table-column>
        <el-table-column prop="payout" label="派彩"> </el-table-column>
        <el-table-column v-for="(item, key) in getLevelCols(1)" :key="key" :prop="key" :label="getLabel(key)">
          <el-table-column :prop="'levels.' + key + '.localPnl'" label="输/赢"></el-table-column>
          <el-table-column :prop="'levels.' + key + '.localNettCommission'" label="佣金"></el-table-column>
          <el-table-column :prop="'levels.' + key + '.localTotal'" label="总计"></el-table-column>
        </el-table-column>
        <el-table-column prop="loginLevelWinLoss" label="公司"> </el-table-column>
      </el-table>
    </div>
  </div>
</div>
</div>
`

const format = (obj) => {
  Object.keys(obj).forEach(key => {
    const val = obj[key]
    if (typeof val === 'number') {
      if ((val + '').indexOf('.') > -1) {
        obj[key] = val.toFixed(2).replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,')
      }
    } else if (typeof val === 'object' && val) {
      format(val)
    }
  })
  return obj
}

const listToFixed = (list) => {
  for (let i = 0; i < list.length; i++) {
    const item = list[i]
    if (typeof item === 'object' && item) {
      format(item)
    }
  }
  return list
}

export default {
  methods: {
    getPingboItemData (item, index) {
      this.loading = true
      this.$set(this.accountList[index], 'statusText', '请求中...')
      this._getPingboItem(item)
        .then(res => {
          console.log(res)
          if (res && res.length) {
            let { name } = item
            if (this.startDate && this.endDate) {
              name = this.startDate.substring(5) + '-' + this.endDate.substring(5) + '——' + name
            }
            console.log(res)
            const list = listToFixed(res)
            const data = [{ name, data: list }]
            const tplData = getTpl({ template: pingboTpl, data: { list: data }, methods: pingboMethods })
            this.sendToMainProcess(`${name}.html`, tplData)
          }
          if (!res || res.length === 0) {
            this.$set(this.accountList[index], 'statusText', '数据为空')
          } else {
            this.$set(this.accountList[index], 'statusText', '请求成功')
          }
        })
        .catch(e => {
          this.$set(this.accountList[index], 'statusText', e || '请求失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    getAllPingboData (reGetList) {
      this.loading = true
      const list = reGetList || this.accountList
      const len = list.length
      let index = 0
      const callback = () => {
        if (this.waitExportList.length === 0) {
          return this.$message.info('请求数据为空')
        }
        let name = this.waitExportList.map(e => e.name).join('、')
        if (this.startDate && this.endDate) {
          name = this.startDate.substring(5) + '-' + this.endDate.substring(5) + '——' + name
        }
        const tplData = getTpl({ template: pingboTpl, data: { list: this.waitExportList }, methods: pingboMethods })
        this.sendToMainProcess(`${name}.html`, tplData)
        this.loading = false
      }
      for (let i = 0; i < len; i++) {
        const item = list[i]
        const itemIndex = this.accountList.findIndex(a => a.name === item.name)
        this.$set(this.accountList[itemIndex], 'statusText', '请求中...')
        this._getPingboItem(item)
          .then(data => {
            if (data && data.length) {
              // allData.push({
              //   name: item.name,
              //   data: listToFixed(data)
              // })
              this.waitExportList.push({
                name: item.name,
                data: listToFixed(data)
              })
              this.$set(this.accountList[itemIndex], 'statusText', '请求成功')
            } else {
              this.$set(this.accountList[itemIndex], 'statusText', '数据为空')
            }
          })
          .catch(e => {
            console.error(e)
            this.errorList.push(item)
            this.$set(this.accountList[itemIndex], 'statusText', e && typeof e === 'string' ? e : '请求失败')
          })
          .finally(() => {
            index = index + 1
            if (index === len) {
              // callback()
              this.loading = false
              this.checkExistErrorList(() => callback())
            }
          })
      }
    },
    _getPingboItem (item) {
      return new Promise((resolve, reject) => {
        const { name, psw, code } = item
        const children = this.getChilren(item.children)
        const { startDate, endDate } = this
        const baseUrl = getCurWebsite()
        const url = baseUrl + '/pingbo/gen'
        // eslint-disable-next-line eqeqeq
        const data = {
          username: name,
          pwd: psw,
          safecode: code,
          date_start: startDate,
          date_end: endDate,
          children: children && children.length ? children : []
        }
        http({
          method: 'post',
          url,
          withCredentials: false,
          data
        }).then(res => {
          if (this.checkSuccess(res)) {
            resolve(res.data.data)
          } else {
            reject(res && res.data && res.data.message)
          }
        }).catch(e => {
          console.error('Report Error: ', e)
          reject(e)
        })
      })
    }
  }
}
